var tokenKey = "token";
//请求url;引用的是env.config.js中对应环境的
var serverUrl = env.env.VUE_APP_BASE_URL;
var userInfo = wx.getStorageSync('userInfo');
import env from '../config/env.config'

// 例外不用token的地址
var exceptionAddrArr = ['/login'];
//请求头处理函数
function CreateHeader(url, type) {
  let header = {}
  if (type == 'POST_PARAMS') {
    header = {
      'content-type': 'application/x-www-form-urlencoded',
    }
  } else {
    header = {
      'content-type': 'application/json',
    }
  }
  if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不需要token的地址
    let token = wx.getStorageSync('token');
    // header.Authorization = token;
    //请求头携带token还有租户id
    header['Token'] = token;
    // header['tenant-id'] = tenantid;
  }
  return header;
}
//post请求，数据在body中
function postRequest(url, data) {
  wx.showLoading()
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: {
        ...data,
        // tenantId: tenantid
      },
      header: header,
      method: 'POST',
      success: (res => {
        console.log(res.data, 'es.data')
        if (res.data && ((typeof res.data.errCode == 'number' && res.data.errCode == 0) || res.data.code === 200)) {
          resolve(res.data)
        }
        //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          //移除失效token
          wx.removeStorageSync('token')
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          console.log("TOKEN失效");
          wx.showToast({
            icon: "none",
            title: (res.data && (res.data.errMsg || res.data.msg)) || "请求失败",
          });
          resolve(res.data)
          //属于tabbar的页面，只能通过wx.switchTab来跳转
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg || res.data.msg) || "请求失败",
          });
          reject(res)
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      }),
      fail: (res => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}

function newPostRequest(url, data) {
  let header = CreateHeader(url, 'POST');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: {
        ...data,
        // tenantId: tenantid
      },
      header: header,
      method: 'POST',
      success: (res => {
        console.log(res.data, 'es.data')
        if (res.data && ((typeof res.data.errCode == 'number' && res.data.errCode == 0) || res.data.code === 200)) {
          resolve(res.data)
        }
        //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          //移除失效token
          wx.removeStorageSync('token')
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          console.log("TOKEN失效");
          wx.showToast({
            icon: "none",
            title: (res.data && (res.data.errMsg || res.data.msg)) || "请求失败",
          });
          resolve(res.data)
          //属于tabbar的页面，只能通过wx.switchTab来跳转
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg || res.data.msg) || "请求失败",
          });
          reject(res)
        }
      }),
      fail: (res => {
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}

//post请求，数据按照query方式传给后端
function postParamsRequest(url, data) {
  wx.showLoading()
  let header = CreateHeader(url, 'POST_PARAMS');
  let useurl = url;
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + useurl,
      header: header,
      method: 'POST',
      success: (res => {
        if (res.data && ((typeof res.data.errCode == 'number' && res.data.errCode == 0) || res.data.code === 200)) {
          resolve(res.data)
        }
        //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          //属于tabbar的页面，只能通过wx.switchTab来跳转
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          //移除失效token
          wx.removeStorageSync('token')
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });
          resolve(res.data)
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });

          reject(res)
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      }),
      fail: (res => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}
//get 请求
function getRequest(url, data) {
  wx.showLoading()
  let header = CreateHeader(url, 'GET');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'GET',
      success: (res => {
        //统一处理响应状态码
        if (res.data && ((typeof res.data.errCode == 'number' && res.data.errCode == 0) || res.data.code === 200)) {
          resolve(res.data)
        } //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          //属于tabbar的页面，只能通过wx.switchTab来跳转
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          //移除失效token
          wx.removeStorageSync('token')
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });
          resolve(res.data)
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });

          reject(res)
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      }),
      fail: (res => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}
//put请求
function putRequest(url, data) {
  wx.showLoading()
  let header = CreateHeader(url, 'PUT');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'PUT',
      success: (res => {
        if (res.data && typeof res.data.errCode == 'number' && res.data.errCode == 0) {
          resolve(res.data)
        } //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          //移除失效token
          wx.removeStorageSync('token')

          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });
          resolve(res.data)
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });

          reject(res)
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      }),
      fail: (res => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}
//delete请求
function deleteRequest(url, data) {
  wx.showLoading()
  let header = CreateHeader(url, 'DELETE');
  return new Promise((resolve, reject) => {
    wx.request({
      url: serverUrl + url,
      data: data,
      header: header,
      method: 'DELETE',
      success: (res => {
        if (res.data && typeof res.data.errCode == 'number' && res.data.errCode == 0) {
          resolve(res.data)
        } //Token失效  跳转至登录页面
        else if (res.data.errCode == 401) {
          //移除失效token
          wx.removeStorageSync('token')
          //移除失效的用户信息
          wx.removeStorageSync('userInfo')
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });
          //属于tabbar的页面，只能通过wx.switchTab来跳转
          wx.redirectTo({
            url: '/pages/auth/login/login'
          })
          resolve(res.data)
        } else {
          wx.showToast({
            icon: "none",
            title: (res.data && res.data.errMsg) || "请求失败",
          });

          reject(res)
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      }),
      fail: (res => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}

function wxUploadFile({ url, filePath, formData }) {
  wx.showLoading()
  let token = wx.getStorageSync('token');
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: serverUrl + url, //仅为示例，非真实的接口地址
      filePath,
      name: 'file',
      formData,
      header: {
        Token: token,
      },
      success(res) {
        console.log(res, 'res')
        const data = res.data;
        let newData = null;
        try {
          newData = JSON.parse(data);
        } catch (error) {

        }
        if (newData && newData.code === 200) {
          resolve(newData);
        } else {
          reject(data);
        }
        setTimeout(_ => {
          wx.hideLoading();
        }, 500)
      },
      fail: (err => {
        wx.hideLoading();
        console.log("err!!!!", err)
        wx.showToast({
          icon: "none",
          title: '请求失败',
        });
        reject(err)
      })
    })
  })
}

module.exports.getRequest = getRequest;

module.exports.newPostRequest = newPostRequest;
module.exports.postRequest = postRequest;
module.exports.postParamsRequest = postParamsRequest;
module.exports.putRequest = putRequest;
module.exports.deleteRequest = deleteRequest;
module.exports.wxUploadFile = wxUploadFile;